<?php
namespace app\admin\controller;

use app\admin\model\AdminLog;
use app\common\model\Admin as AdminModel;
use app\common\model\Roles;
use app\common\model\SystemMenu;
use think\captcha\Captcha;
use think\Db;
use think\facade\Session;

/**
 * 管理员控制器
 * Class Admin
 * @package app\admin\controller
 */
class Admin extends Base
{
    /**
     * 用户登录
     * @return mixed
     */
    public function login(){

        if($this->request->method() === "POST"){

            $captcha = new Captcha();
            $value = $this->request->post('vertify');
            if( !$captcha->check($value))
            {
                return $this->error('验证码错误');
            }
            $username = trim($this->request->post('username'));
            $password = trim($this->request->post('password'));
            if($username==''){
                return $this->error('用户名不能为空！');
            }
            if($password == ''){
                return $this->error('密码不能为空！');
            }
            $user = AdminModel::with('role')->where('adm_username',$username)->find();
            if(!$user){
                return $this->error('当前账号不存在！');
            }
            if(!password_verify($password,$user['adm_password'])){
                return $this->error('密码输入错误！');
            }
                Session::set('adm_id',$user['adm_id'],'admin');
                Session::set('adm_username',$user['adm_username'],'admin');
                Session::set('last_login',$user['adm_last_login'],'admin');
                Session::set('last_ip',$user['adm_last_ip'],'admin');
                //更新数据
                AdminModel::where('adm_id',$user['adm_id'])->update(['adm_last_login'=>time(),'adm_last_ip'=>$this->request->ip()]);
                Session::set('role_list',$user['role']['role_auth_id'],'admin');

                $this->create_log('后台登录',$this->request->url());//管理日志

                return $this->success('登录成功！',url('Admin/index/index'));

        }
        return $this->fetch();
    }

    /**
     * 推出登录
     */
    public function logout(){
        Session::clear('admin');
        return $this->success("退出成功",url('Admin/login'),'',2);
    }

    /**
     * 验证码生成
     * @return \think\Response
     */
    public function captcha(){
        $config = [
            'fontSize'=>40,
            'length'=>4,
            'useCurve'=>false,
            'reset' =>true,
            'expire' =>1800
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }

    /*
	 * 管理员列表
	 */
    public function index()
    {
        $admins =AdminModel::with('role')->order('adm_id','asc')->select();
        $this->assign('list',$admins);
        return $this->fetch();
    }

    /**
     * 添加管理员
     */
    public function add_admin()
    {
        $id=$this->request->param('adm_id',0);
        $admin = AdminModel::get($id);
        $this->assign('info',$admin);
        $act = isset($admin)?'edit':'add';
        $role = Roles::where('role_type','admin')->select();
        $this->assign('act',$act);
        $this->assign('role',$role);
        return $this->fetch();
    }

    /**
     * 执行添加管理员操作
     */
    public function submint_admin(){
        if($this->request->method()==="POST"){
            $param = $this->request->except('act');
            if($param['adm_id']){
                $output = AdminModel::update($param);
            }else{
                $param['adm_password'] = encrypt($param['adm_password']);
                $param['adm_create_time'] = time();
                $output = AdminModel::create($param);
            }
            if($output){
                return $this->success('操作成功！','admin/index','','1');
            }else{
                return $this->error('操作失败！','','1');
            }
        }

    }

    /**
     * 管理员删除管理
     */
    public function del_admin(){
        $id = $this->request->param('adm_id');
        $output = AdminModel::destroy($id);
        if($output){
            return $this->success('删除成功');
        }else{
            return $this->error('删除失败！');
        }
    }

    /**
     * ajax验证用户名是否存在
     */
    public function ajaxUsername()
    {
        $name = $this->request->param('name');
        $param = $this->request->param('param');
        if(!ajaxExist($name,$param,'admin')){
            return array("info"=>"验证通过！",
			"status"=>"y");
        };
        return array("info"=>'管理账号已存在！',"status"=>"n");
    }

    /**
     * 角色管理
     */
    public function role(){
        $list = Roles::where('role_type','admin')->where('role_auth_id','neq','all')->select();
        $this->assign('list',$list);
        return $this->fetch();
    }

    /**
     * 角色表单
     */
    public function add_role(){
        $role_id = $this->request->param('role_id',0);
        $list = Roles::get($role_id);
        $detail = explode(',',$list['role_auth_id']);
        $this->assign('detail',$detail);
        $this->assign('info',$list);
        $this->assign('act','add');

        $right = SystemMenu::all();//所有权限资源
        foreach($right as $v){
            $v['enable'] = in_array($v['sm_id'],$detail);//根据该字段判断是否已选择
            $modules[$v['sm_group']][] = $v;
        }

        $this->assign('mod','admin');
        $this->assign('modules',$modules);//权限资源分组
        $this->assign('rolemenu',getRoleMenu());//权限资源分组
        return $this->fetch();
    }

    /**
     * 角色添加修改
     */
    public function submit_role(){
        if($this->request->method() === "POST"){
            $param = $this->request->except('right');
            $right = $this->request->post('right/a');
            if(!is_array($right)){
                return $this->error('权限至少选择一项！');
            }
            $param['role_auth_id'] = implode(',',$right);
            if($param['role_id']){
                $output = Roles::update($param);
            }else{
                $output = Roles::create($param);
            }
            if($output){
                $this->success('操作成功！',url('admin/role'),'',1);
            }else{
                $this->error('操作失败！');
            }
        }
    }

    /**
     * 角色删除
     */
    public function del_role(){
        $id = $this->request->post('role_id');
        $output = Roles::destroy($id);
        if($output){
            return $this->success('删除成功');
        }else{
            return $this->error('删除失败！');
        }
    }

    /**
     * 管理操作日志
     */
    public function log(){
        $adminlog = AdminLog::with('admin')->order('log_time','desc')->paginate(10,false,[
            'type'     => 'bootstrap',
        ]);
        $page = $adminlog->render();
        $this->assign('page',$page);
        $this->assign('list',$adminlog);
        return $this->fetch();
    }
}